#! /usr/bin/env python

import os
import re
import shutil
import markitdown
from datetime import date
import sys
from rich import print as rprint
from openpyxl import Workbook

import re
from datetime import datetime

sys.path.append("../lib")

from inner_util import prepare_dir, get_files

SRC_DIR = sys.argv[1]


def remove_whitespace_except_newlines(text):
    # 使用正则表达式替换除换行符以外的空白字符
    # \s 匹配所有空白字符，包括空格、制表符等
    # [^\S\n] 匹配所有非换行符的空白字符
    cleaned_text = re.sub(r"[^\S\n]+", "", text)
    return cleaned_text


class DateDoc:
    def __init__(self, file_path):
        self.file_path = file_path
        self.content = ""
        res = self.convert()
        if res and res.text_content:
            self.content = remove_whitespace_except_newlines(res.text_content)

        print("kan", self.content)

    def convert(self):
        md = markitdown.MarkItDown()
        try:
            res = md.convert(self.file_path)
            return res
        except markitdown._markitdown.UnsupportedFormatException as e:
            print("Error", e)
            log_err(f"{self.file_path} {str(e)} 不支持的格式")
            return None

    def get_first_date(self):
        no_white_content = re.sub(r"\s*", "", self.content)
        last_mat = ""
        mat = re.search(r"(\d{4})年(\d{1,2})月(\d{1,2})日", no_white_content)
        if mat:
            print("Date", mat.string[mat.start() : mat.end()])
            last_mat = mat.groups()
            y, m, d = last_mat
            meeting_date = date(year=int(y), month=int(m), day=int(d))
            return meeting_date.strftime("%Y.%m.%d")
        return last_mat

    def parse(self):
        paste_string = self.content

        if paste_string == "":
            return None

        doc = {
            "title": "",
            "code": "",
            "send_by": "",
            "send_to": "",
            "send_date": datetime.now().strftime("%Y-%m-%d"),
            "meeting_date": self.get_first_date(),
        }

        def get_index_num(rows: list, reg_exp: re.Pattern) -> int:
            index = -1
            for i, row in enumerate(rows):
                if reg_exp.match(row):
                    index = i
                    break
            return index

        # Split by line, clean up whitespace
        rows = []
        for v in paste_string.split("\n"):
            if v.strip() != "":
                v = re.sub(r"[\s\t]", "", v)
                v = re.sub(r"[\(（]", "（", v)
                v = re.sub(r"[\)）]", "）", v)
                rows.append(v)

        if len(rows) > 1:
            # Line by line processing
            reg_code = re.compile(r"\S+〔\d{4}〕\d+号")
            reg_title = re.compile(r"\S+[请示|函|通知|报告|意见|批复]$")
            reg_send_to = re.compile(r"\S+[:：]$")
            reg_send_date = re.compile(r"^\d{4}年\d{1,}月\d{1,}日$")

            code_row = get_index_num(rows, reg_code)
            send_to_end_row = get_index_num(rows, reg_send_to)
            title_end_row = get_index_num(rows, reg_title)
            send_date_row = get_index_num(rows, reg_send_date)

            if code_row != -1:
                reg_code_match = re.compile(r"(\S+〔\d{4}〕\d+号)")
                code_mat = reg_code_match.search(rows[code_row])
                if code_mat:
                    doc["code"] = code_mat.group(1)

            if title_end_row != -1 and send_to_end_row != -1:
                doc["send_to"] = "".join(
                    rows[title_end_row + 1 : send_to_end_row + 1]
                ).replace("[:：]", "")
                doc["title"] = "".join(rows[code_row + 1 : title_end_row + 1])

            if send_date_row != -1:
                doc["send_date"] = datetime.strptime(
                    rows[send_date_row], "%Y年%m月%d日"
                ).strftime("%Y-%m-%d")

            if doc["title"] == "":
                doc["title"] = "".join(rows)

        else:
            # No line splitting processing
            reg_all = re.compile(
                r"((\S+)文件)*(\S+〔\d{4}〕\d+号)*(\S*的(请示|函|通知|报告|意见|批复))(\S+)[:：]"
            )
            matches = reg_all.search(rows[0])
            if matches:
                doc["send_by"] = [matches.group(2)] if matches.group(2) else []
                doc["code"] = matches.group(3) if matches.group(3) else ""
                doc["title"] = matches.group(4) if matches.group(4) else ""
                doc["send_to"] = matches.group(6) if matches.group(6) else ""
            else:
                doc["title"] = paste_string

        return doc


def log_err(err):
    with open("err.log", "a+", encoding="utf-8") as f:
        f.write(err)


def convert_file(file_path):
    md = markitdown.MarkItDown()
    try:
        res = md.convert(file_path)
        return res
    except markitdown._markitdown.UnsupportedFormatException as e:
        print("Error", e)
        log_err(f"{file_path} {str(e)} 不支持的格式")
        return None


def write_file(file_path, content):
    with open(f"dist/{file_path}.txt", "w", encoding="utf-8") as f:
        f.write(content)


def get_first_date(content):
    last_mat = None
    mat = re.search(r"(\d{4})年(\d{1,2})月(\d{1,2})日", content)
    if mat:
        print("Date", mat.string[mat.start() : mat.end()])
        last_mat = mat.groups()
    return last_mat


def parse_row(paste_string: str) -> dict:
    doc = {
        "title": "",
        "code": "",
        "send_by": "",
        "send_to": "",
        "send_date": datetime.now().strftime("%Y-%m-%d"),
    }

    def get_index_num(rows: list, reg_exp: re.Pattern) -> int:
        index = -1
        for i, row in enumerate(rows):
            if reg_exp.match(row):
                index = i
                break
        return index

    # Split by line, clean up whitespace
    rows = []
    for v in paste_string.split("\n"):
        if v.strip() != "":
            v = re.sub(r"[\s\t]", "", v)
            v = re.sub(r"[\(（]", "（", v)
            v = re.sub(r"[\)）]", "）", v)
            rows.append(v)

    if len(rows) > 1:
        # Line by line processing
        reg_code = re.compile(r"\S+〔\d{4}〕\d+号")
        reg_title = re.compile(r"\S+[请示|函|通知|报告|意见|批复]$")
        reg_send_to = re.compile(r"\S+[:：]$")
        reg_send_date = re.compile(r"^\d{4}年\d{1,}月\d{1,}日$")

        code_row = get_index_num(rows, reg_code)
        send_to_end_row = get_index_num(rows, reg_send_to)
        title_end_row = get_index_num(rows, reg_title)
        send_date_row = get_index_num(rows, reg_send_date)

        if code_row != -1:
            reg_code_match = re.compile(r"(\S+〔\d{4}〕\d+号)")
            code_mat = reg_code_match.search(rows[code_row])
            if code_mat:
                doc["code"] = code_mat.group(1)

        if title_end_row != -1 and send_to_end_row != -1:
            doc["send_to"] = "".join(
                rows[title_end_row + 1 : send_to_end_row + 1]
            ).replace("[:：]", "")
            doc["title"] = "".join(rows[code_row + 1 : title_end_row + 1])

        if send_date_row != -1:
            doc["send_date"] = datetime.strptime(
                rows[send_date_row], "%Y年%m月%d日"
            ).strftime("%Y-%m-%d")

        if doc["title"] == "":
            doc["title"] = "".join(rows)
        else:
            doc["send_by"] = doc["title"].split("关于")[0]

    else:
        # No line splitting processing
        reg_all = re.compile(
            r"((\S+)文件)*(\S+〔\d{4}〕\d+号)*(\S*的(请示|函|通知|报告|意见|批复))(\S+)[:：]"
        )
        matches = reg_all.search(rows[0])

        print("matts", matches)
        if matches:
            doc["send_by"] = [matches.group(2)] if matches.group(2) else ""
            doc["code"] = matches.group(3) if matches.group(3) else ""
            doc["title"] = matches.group(4) if matches.group(4) else ""
            doc["send_to"] = matches.group(6) if matches.group(6) else ""
        else:
            doc["title"] = paste_string

    return doc


def report(docs):
    wb = Workbook()
    ws = wb.active
    # 序号	培训时间	培训施教机构	培训内容	培训类别	培训方式	学时	备注

    ws.append(
        [
            "序号",
            "培训时间",
            "培训施教机构",
            "培训内容",
            "培训类别",
            "培训方式",
            "学时",
            "备注",
        ]
    )

    for d in docs:
        print("d", d)
        ws.append(["", d["meeting_date"], d["send_by"], d["title"], "", "", "", ""])

    wb.save("dist.xlsx")


def main():
    print("Start")

    prepare_dir("dist")

    error_files = []

    valid_exts = [".docx", ".pdf", ".doc", ".wps"]
    all_files = get_files(SRC_DIR, valid_exts, recursive=True)

    # print("All files", all_files)
    docs = []

    for f in all_files:
        res = DateDoc(f)
        doc = res.parse()
        if doc:
            rprint("dddo", doc)
            docs.append(doc)

        continue

        res = convert_file(f)
        name = os.path.basename(f)
        print("---------------------------")
        print("Parse", name)

        if res is None:
            print("Warning", f)
            error_files.append(("没内容", f))
            shutil.copy(f, f"dist/{name}")
            continue

        target_file = name

        a = parse_row(res.text_content)
        rprint("a", a)

        content = re.sub(r"\s*", "", res.text_content)

        mat = get_first_date(content)
        if mat:
            y, m, d = mat
            metting_date = date(year=int(y), month=int(m), day=int(d))
            target_file = f"{metting_date.strftime('%Y%m%d')}-{name}"
        else:
            error_files.append(("没有日期", f))

        shutil.copy(f, f"dist/{target_file}")

    rprint("Error files", error_files)

    report(docs)
    # write_file(target_file, res.text_content)


if __name__ == "__main__":
    main()
